package com.education.module.system.user;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;

import com.education.domain.User;
import com.education.framework.base.BaseServices;
import com.education.framework.dao.IDao;
import com.education.framework.domain.SearchParams;
import com.education.framework.page.Page;
import com.education.framework.util.Md5Util;
import com.education.module.system.sysRole.SysRoleServices;

@Service
public class UserServices extends BaseServices implements IDao<User>{
	@Autowired
	private SysRoleServices services;
	
	public User findUserByLoginName(String loginName){
		String sql = "select id,loginname,passwd,truename,role_id,gender,orgid,orgname,remark,telephone,address,email,cardNumber from sys_user where loginname=?";
		Object[] args = {loginName};
		
		List<User> list = dao.query(sql, args,new UserRowmapper());
		User loginUser = null;
		if(null != list && list.size() >= 1){
			loginUser = list.get(0);
		}
		return loginUser;
	}
	
	@Override
	public boolean findIsExist(String name){
		//验证LOGINNAME是否已存在
		String sqlQuery = "select count(id) from sys_user where loginname=?";
		return dao.queryForInt(sqlQuery,new Object[]{name}) == 0 ? false : true;
	}
	
	@Override
	public int save(User user) {
		StringBuffer sql = new StringBuffer(); 
		sql.append("insert into sys_user ( "); 
		sql.append("loginname,passwd,truename,gender "); 
		sql.append(",orgid,orgname,remark "); 
		sql.append(",telephone,address,email,create_user,update_user,cardNumber,role_id ");  
		sql.append(" ) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?) "); 
		Object[] args = {user.getLoginName(), Md5Util.MD5Encode(user.getPasswd()),user.getTrueName(),user.getGender(),user.getOrgId() 
		 ,user.getOrgName(),user.getRemark(),user.getTelephone(),user.getAddress() 
		 ,user.getEmail(),user.getCreateUser().getId(),user.getUpdateUser().getId(),user.getCardNumber(),user.getSysRole().getId() };
		
		dao.update(sql.toString(), args);
		return dao.queryForInt("SELECT LAST_INSERT_ID()"); 
	}

	@Override
	public User findForObject(Integer id) {
		String sql = "select id,loginname,passwd,truename,role_id,gender,orgid,orgname,remark,telephone,address,email,cardNumber from sys_user where id=?";
		Object[] args = {id};
		return dao.queryForObject(sql, args,new UserRowmapper());
	}

	@Override
	public void update(User user) {
		 StringBuffer sql = new StringBuffer(); 
		 sql.append("update sys_user "); 
		 sql.append("set  "); 
		 if(!"".equals(user.getPasswd())){
			 sql.append("passwd=?,");
		 }
		 sql.append("loginname=?,truename=?,gender=? "); 
		 sql.append(",orgid=?,orgname=?,remark=? "); 
		 sql.append(",telephone=?,address=?,email=?,cardNumber=?,role_id=? "); 
		 sql.append(" where id=? ");
		 Object[] args = null;
		 if(!"".equals(user.getPasswd())){
			 args = new Object[]{ Md5Util.MD5Encode(user.getPasswd()),user.getLoginName(),user.getTrueName(),user.getGender(),user.getOrgId() 
					 ,user.getOrgName(),user.getRemark(),user.getTelephone(),user.getAddress() 
					 ,user.getEmail(),user.getCardNumber() , user.getSysRole().getId() ,user.getId()};
		 }else{
			 args = new Object[]{user.getLoginName(),user.getTrueName(),user.getGender(),user.getOrgId() 
					 ,user.getOrgName(),user.getRemark(),user.getTelephone(),user.getAddress() 
					 ,user.getEmail(),user.getCardNumber() , user.getSysRole().getId() ,user.getId()};
		 }
		 
		 
		 dao.update(sql.toString(), args);
	}

	@Override
	public void delete(Integer id) {
		String sql = "delete from sys_user where id=?";
		dao.update(sql,new Object[]{id});
	}

	private class UserRowmapper implements RowMapper<User> {
		@Override
		public User mapRow(ResultSet rs, int arg1) throws SQLException {
			User user = new User();
			user.setId(rs.getInt("id"));
			user.setLoginName(rs.getString("loginname"));
			user.setPasswd(rs.getString("passwd"));
			user.setTrueName(rs.getString("truename"));
			user.setGender(rs.getString("gender"));
			user.setOrgId(rs.getInt("orgid"));
			user.setOrgName(rs.getString("orgname"));
			user.setRemark(rs.getString("remark"));
			user.setTelephone(rs.getString("telephone"));
			user.setAddress(rs.getString("address"));
			user.setEmail(rs.getString("email"));
			user.setCardNumber(rs.getString("cardNumber"));
			int roleId = rs.getInt("role_id");
			user.setSysRole(services.findForObject(roleId));
			return user;
		}
	}
	
	@Override
	public List<User> find(SearchParams searchParams, Page page) {
		StringBuffer sql = new StringBuffer("select id,loginname,passwd,truename,role_id,gender,orgid,orgname,remark,telephone,address,email,cardNumber from sys_user ");
		StringBuffer sqlCase = new StringBuffer();
		String lp = " where ";
		List<Object> argsList = new ArrayList<Object>();
		if(null != searchParams){
			if(null != searchParams.get("loginName") && !"".equals((String)searchParams.get("loginName"))){
				sqlCase.append(lp).append(" loginname=? ");
				argsList.add(searchParams.get("loginName"));
				lp = " and ";
			}
		}
		Object[] args = argsList.toArray();
		sql.append(sqlCase.toString());
		sql.append(" order by update_time desc ");
		List<User> list = dao.query(pageSQL(sql.toString(),page),args,new UserRowmapper());
		page.setTotalItem(findRecordCount("select count(id) as cNum from sys_user " + sqlCase.toString(),args));
		return list;
	}

	public boolean updatePasswd(Integer id, String passwd) {
		StringBuffer sql = new StringBuffer();
		sql.append("update sys_user set passwd=? where id=?");
		return dao.update(sql.toString(), new Object[]{Md5Util.MD5Encode(passwd),id})>0;
	}

}
